package com.sky.aop;

import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import com.sky.exception.AopAutoFillException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect

public class AutoAspect {
    @Pointcut(value = "@annotation(com.sky.aop.AutoFill)")
    public void autoFillPointCut(){};
    @Before("autoFillPointCut()")
    public void autoFillInsert(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        try {
            Object[] args = joinPoint.getArgs();
            Object entity=args[0];
            MethodSignature signature =(MethodSignature) joinPoint.getSignature();
            OperationType value = signature.getMethod().getAnnotation(AutoFill.class).value();
            Class<?> aClass = entity.getClass();
            Method setCreateTime = aClass.getMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
            Method setCreateUser = aClass.getMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
            Method setUpdateTime = aClass.getMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
            Method setUpdateUser = aClass.getMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);

            if (value==OperationType.INSERT){
            setCreateUser.invoke(entity,BaseContext.getCurrentId());
            setCreateTime.invoke(entity,LocalDateTime.now());
            setUpdateTime.invoke(entity,LocalDateTime.now());
            setUpdateUser.invoke(entity,BaseContext.getCurrentId());
            }
            if (value==OperationType.UPDATE){
                setUpdateTime.invoke(entity,LocalDateTime.now());
                setUpdateUser.invoke(entity,BaseContext.getCurrentId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new AopAutoFillException("aop自动填充异常");
        }
    }


}
